﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;

namespace ReactiveCode.Statements
{
    class ReturnStatement<T>: ReactiveStatement
    {
        public IObservable<T> Value { get; private set; }

        public ReturnStatement(ObservableFactory<IObservable<T>> value)
        {
            Contract.Requires(value != null);
            this.Value = Extract(value);
            EnabledProperty.Subscribe(x =>
            {
                foreach (var stmt in this.MeAndAncestors())
                {
                    var parentBlock = stmt.Parent as Block;
                    if (parentBlock != null)
                    {
                        if (x)
                            parentBlock.Disablers.Add(stmt);
                        else
                            parentBlock.Disablers.Remove(stmt);
                    }

                    var body = stmt as ReactiveMethod.BodyStatement;
                    if (body != null)
                    {
                        var method = (ReactiveMethod<T>)body.Method;
                        if (x)
                            method.CurrentReturnStatement = this;
                        else if (method.CurrentReturnStatement == this)
                            method.CurrentReturnStatement = null;
                        break;
                    }
                }
            });
        }
    }
}
